import React, { useEffect } from 'react';
import style from './App.module.css';
import {BrowserRouter, Route, Routes, Link } from 'react-router-dom'
import { 
  HomePage, 
  SingIn, 
  Register, 
  Detail, 
  Search, 
  ShoppingCart,
  PlaceOrder
} from './pages'
// import {  } from 'react-router-dom'
import { useSelector } from './redux/hooks'
import { useDispatch } from 'react-redux'
import { getShoppingCart } from './redux/shoppingCart/slice'
import { searchProduct } from './redux/productSearch/slice'

// isAuthenticated判定是否登录
// ...rest其他props属性
// const PrivateRoute = ({ component, isAuthenticated, ...rest }) => {
//   const routeComponent = (props) => {
//     // React.createElement()创建组件
//     return isAuthenticated ? React.createElement(component, props)
//     : <Link to="/signIn">
//       </Link>
//   }
//   return <Route path="/shoppingCart" element={routeComponent} {...rest}></Route>
// }


function App() {
  const jwt = useSelector((s) => s.user.token)
  const dispatch = useDispatch()

  useEffect(() => {
    // App启动时加载购物车数据
    if (jwt) {
      dispatch(getShoppingCart(jwt))
      dispatch(searchProduct({nextPage: 1, pageSize: 10, keywords: '1'}))
    }
  }, [jwt])

  return (
    <div className={style.App}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<HomePage></HomePage>}></Route>
          <Route path="/signIn" element={<SingIn></SingIn>}></Route>
          <Route path="/register" element={<Register></Register>}></Route>
          <Route path="/detail/:id" element={<Detail></Detail>}></Route>
          <Route path="/search/:keywords" element={<Search></Search>}></Route>
          {
            jwt ? <Route path="/shoppingCart" element={<ShoppingCart></ShoppingCart>}></Route> : false
          }
          {
            jwt ? <Route path="/placeOrder" element={<PlaceOrder></PlaceOrder>}></Route> : false
          }
          <Route path="*" element={<h1>404</h1>}></Route>
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;
